//
//  OADetailDisPatchController.m
//  maocuhuiOASystem
//
//  Created by michael on 16/3/22.
//  Copyright © 2016年 czd. All rights reserved.
//
#import "OANameListController.h"
#import "OAExpendViewController.h"
#import "OADetailDisPatchController.h"
#import "OADetailDisPatchCell.h"
#import "GDataDefines.h"
#import <QuickLook/QuickLook.h>
#import "OAHistroyViewController.h"
#import "OAAttachmentsModel.h"
#import "OASelectDepartmentController.h"
#import "OADepartmentModel.h"
#import "OADetailDispatchModel.h"
#import "OAReadRecordController.h"

@interface detailViewController ()<UIWebViewDelegate,QLPreviewControllerDataSource,QLPreviewControllerDelegate>
@property(nonatomic,strong)OADetailDispatchModel * detailPatchModel ;
@property(nonatomic,strong)NSMutableArray * attachmentArray; //附件
@property(nonatomic,strong)NSMutableArray * mainattachmentArray; //正文附件
@property(nonatomic,strong)NSString * attacmentURL;
@property(nonatomic,strong)NSMutableArray * contentsData;

@property(nonatomic,assign)BOOL isEditoring; //编辑中
@property(nonatomic,strong)NSMutableArray * departments;

@property(nonatomic,copy)NSString * infoString; //服务器返回字段 根据该字段跳转不同的界面
@property(nonatomic,copy)NSString * textString ; //记录填写的意见
@property(nonatomic,copy)NSString * body;
@property(nonatomic,strong)NSMutableArray * subItems;  //选中 需要提交得数据


@end

@implementation detailViewController
-(NSMutableArray*)contentsData{
    if (_contentsData == nil) {
        _contentsData = [NSMutableArray array];
    }
    return _contentsData;
}

-(NSMutableArray*)attachmentArray{
    if (_attachmentArray ==nil) {
        _attachmentArray = [NSMutableArray array];
    }
    return _attachmentArray;
}
-(NSMutableArray*)mainattachmentArray{
    if (_mainattachmentArray == nil) {
        _mainattachmentArray = [NSMutableArray array];
    }
    return _mainattachmentArray;
}
-(NSMutableArray*)subItems{
    if (_subItems ==nil) {
        _subItems = [NSMutableArray array];
    }
    return _subItems;

}


- (void)viewDidLoad {
    [super viewDidLoad];
    // 判断接口
    [self _String];
     self.title = @"详情";
    self.tableView .bounces = NO;
    
   
    self.tableView.hidden = YES;
 //加载网络数据
    [self loadData];
    
}
- (void)_String{

if ([self.type isEqualToString:@"contentDipatch"]) {
self.method = @"contentDipatch";
self.url = KexchgeneralURL;
  UIBarButtonItem * rightItem = [[UIBarButtonItem alloc]initWithTitle:@"阅读记录" style:UIBarButtonItemStylePlain target:self action:@selector(operation)];
    self.navigationItem.rightBarButtonItem = rightItem;

    
}
 else if ([self.type isEqualToString:@"contentIn"]) {
self.method = @"contentIn";
self.url = KexchgeneralURL;
  UIBarButtonItem * rightItem = [[UIBarButtonItem alloc]initWithTitle:@"阅读记录" style:UIBarButtonItemStylePlain target:self action:@selector(operation)];
    self.navigationItem.rightBarButtonItem = rightItem;

    
}else if ([self.type isEqualToString:@"work"]) {
self.method = @"getSwArchiveOffice";
//self.url = kexmoreworkings;
//self.url = KexchdataURL;

self.url = @"http://192.168.100.22:8080/IOSMOA/jh/exchTansaction";
  UIBarButtonItem * rightItem = [[UIBarButtonItem alloc]initWithTitle:@"流转历史" style:UIBarButtonItemStylePlain target:self action:@selector(operation)];
    self.navigationItem.rightBarButtonItem = rightItem;

    

}else if ([self.type isEqualToString:@"work1"]) {
  _url = KexchdataURL;
    _method = KGetOAOfficeMethod;

UIBarButtonItem * rightItem = [[UIBarButtonItem alloc]initWithTitle:@"流转历史" style:UIBarButtonItemStylePlain target:self action:@selector(historyAction)];
 self.navigationItem.rightBarButtonItem = rightItem;

    

}
else if ([self.type isEqualToString:@"dzgg"]){
self.method = KContentElectronicsMethod;
self.url = KexchgeneralURL;
//UIBarButtonItem * rightItem = [[UIBarButtonItem alloc]initWithTitle:@"流转历史" style:UIBarButtonItemStylePlain target:self action:@selector(historyAction)];
// self.navigationItem.rightBarButtonItem = rightItem;
}else if ([self.type isEqualToString:@"gonggao"]){
self.method = @"systemContent";
self.url = KExchmain;

}else if ([self.type isEqualToString:@"work2"]){
self.method = @"getArchiveOffice";
self.url = @"http://192.168.100.22:8080/IOSMOA/jh/exchTansaction";
UIBarButtonItem * rightItem = [[UIBarButtonItem alloc]initWithTitle:@"流转历史" style:UIBarButtonItemStylePlain target:self action:@selector(historyAction)];
 self.navigationItem.rightBarButtonItem = rightItem;
}else if ([self.type isEqualToString:@"chaxun"]) {
self.method = @"getArichiveDoc";
self.url = KexexcharchiveURL;

}else if ([self.type isEqualToString:@"dengji"]){
self.method = @"contentRegbookFile";
self.url = kexchgregbookurl;
 UIBarButtonItem * rightIem = [[UIBarButtonItem alloc] initWithTitle:@"启用流程" style:UIBarButtonItemStylePlain target:self action:@selector(searchAction)];
//        self.navigationItem.rightBarButtonItem = rightIem;

}else if ([self.type isEqualToString:@"shouwen"]){
self.method = @"contentRegbookFile";
self.url = kexchgregbookurl;
// UIBarButtonItem * rightIem = [[UIBarButtonItem alloc] initWithTitle:@"启用流程" style:UIBarButtonItemStylePlain target:self action:@selector(searchAction)];
//        self.navigationItem.rightBarButtonItem = rightIem;

}else if ([self.type isEqualToString:@"shiwei"]){
self.method = @"contentDotwoFile";
self.url = @"exchgdotwo";


}
else if ([self.type isEqualToString:@"zhuanfa"]){
self.method = @"contenttrunMail";
self.url = KexchmailURL;
  UIBarButtonItem *item1 = [[UIBarButtonItem alloc] initWithTitle:@"转发"style:UIBarButtonItemStylePlain target:self action:@selector(rightButtonAction)];

                     self.navigationItem.rightBarButtonItem = item1;
}else if ([self.type isEqualToString:@"kszhuanfa"]){
self.method = @"contenttrunMail";
self.url = KexchksmailURL;
  UIBarButtonItem *item1 = [[UIBarButtonItem alloc] initWithTitle:@"转发"style:UIBarButtonItemStylePlain target:self action:@selector(rightButtonAction)];

                     self.navigationItem.rightBarButtonItem = item1;
}else if ([self.type isEqualToString:@"xxjb"]){
self.method = @"contentxxjbFile";
self.url = KexchxxjbURL;
}



}
- (void)rightButtonAction{

//OAExpendViewController * expendVC = [[OAExpendViewController alloc] init];
////    expendVC.identifierString = listModel.path;
//                         expendVC.hidesBottomBarWhenPushed = YES;
//                                 expendVC.type = UnitDataType;
//expendVC.seltype = _type;
//
//expendVC.field = self.fileId;
//    [self.navigationController pushViewController:expendVC animated:YES];

        OANameListController * listVC = (OANameListController*)[self.storyboard instantiateViewControllerWithIdentifier:@"NameLIstID"];
    listVC.delegate = self;
        listVC.type = @"UnitDataType";
listVC.seltype = _type;
listVC.fileId = self.fileId;
//    self.namelist = listVC;
    [self.navigationController pushViewController:listVC animated:YES];
    
}
- (void)searchAction{
 UIStoryboard * storyBoard = [UIStoryboard storyboardWithName:@"Main" bundle:nil];

         OADetailDisPatchController * detailVC = (OADetailDisPatchController*)[storyBoard instantiateViewControllerWithIdentifier:@"OADetailDispatchVC"];
//    detailVC.fileId = _detailPatchModel.fileId;
    detailVC.fileId = _fileId;

    detailVC.isAlreadDoneWork = YES;
                detailVC.isUnDoWork = NO;
detailVC.type = @"dengji";
    [self.navigationController pushViewController:detailVC animated:YES];

}

-(void)operation{
    OAReadRecordController * readRecordVC = [[OAReadRecordController alloc]init];
    readRecordVC.fileId = self.fileId;
                        readRecordVC.hidesBottomBarWhenPushed = YES;

    [self.navigationController pushViewController:readRecordVC  animated:YES];
}

#pragma mark 流转历史
-(void)historyAction{
    OAHistroyViewController* historyVC = (OAHistroyViewController*)[self.storyboard instantiateViewControllerWithIdentifier:@"HistoryVC"];
    
    historyVC.fileId = self.fileId;
                            historyVC.hidesBottomBarWhenPushed = YES;

    
    [self.navigationController pushViewController:historyVC animated:YES];
}

#pragma mark 加载网络数据
-(void)loadData{
    [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    NSString * userId = [[NSUserDefaults standardUserDefaults]objectForKey:@"userId"];
    if ([_type isEqualToString:@"chaxun"]) {
       _array = @[@{@"userId":userId},@{@"unId":self.fileId},@{@"dbpath":_year}];

}else if ([_type isEqualToString:@"gonggao"]) {
    _array = @[@{@"userId":userId},@{@"unId":self.fileId}];

}else{
    _array = @[@{@"unId":self.fileId},@{@"userId":userId}];
  }
    [HttpTools postWithURL:self.url arrays:_array method:_method success:^(id JSON) {
    
   NSLog(@"====%@",JSON);
        [MBProgressHUD hideAllHUDsForView:self.view animated:YES];
        self.tableView.hidden = NO;
//        ||[self.type isEqualToString:@"shouwen"]||[self.type isEqualToString:@"shiwei"]
    if ([self.type isEqualToString:@"dengji"]) {
    self.detailPatchModel = [self getDetailModel2:JSON];
} else if ([self.type isEqualToString:@"zhuanfa"]||[self.type isEqualToString:@"dzgg"]||[self.type isEqualToString:@"gonggao"]||[self.type isEqualToString:@"shiwei"]||[self.type isEqualToString:@"xxjb"]||[self.type isEqualToString:@"kszhuanfa"]) {
    self.detailPatchModel = [self getDetailModel3:JSON];
}else{
        self.detailPatchModel = [self getDetailModel1:JSON];
        }
        [self.tableView reloadData];
    } failure:^(NSError *error) {
        [MBProgressHUD hideAllHUDsForView:self.view animated:YES];
    }];
    
}
-(OADetailDispatchModel *)getDetailModel3:(NSString*)dataString;
{
    NSData * data = [dataString dataUsingEncoding:NSUTF8StringEncoding];
    OADetailDispatchModel * detailModel = [[OADetailDispatchModel alloc]init];
    GDataXMLDocument *doc = [[GDataXMLDocument alloc] initWithData: data options:0 error:nil];
    //获取根节点（Users）
    GDataXMLElement *rootElement = [doc rootElement];
    //获取根节点下的节点（User）
    NSArray *rootData= [rootElement elementsForName:@"数据"];
    for (GDataXMLElement *data in rootData) {
      
            GDataXMLElement *documentElement= [[data elementsForName:@"文档"] objectAtIndex:0];
            detailModel.document = [documentElement stringValue];
            
            
            
            GDataXMLElement *filestep= [[data elementsForName:@"填写意见环节"] objectAtIndex:0];
            detailModel.flow = [filestep stringValue];
            
            GDataXMLElement *fileId= [[data elementsForName:@"唯一标识"] objectAtIndex:0];
            detailModel.fileId = [fileId stringValue];
            
        
    }
    //index。seston = 2
    for (GDataXMLElement * subData in rootData) {
        NSArray * tempArray = [subData elementsForName:@"数据实体"];
        for (GDataXMLElement * element in tempArray) {
            NSArray *array = [element elementsForName:@"附件"];
            for (GDataXMLElement * data in array) {
                OAAttachmentsModel * attachModel = [[OAAttachmentsModel alloc]init];
                GDataXMLElement * nameElement = [[data elementsForName:@"名称"] objectAtIndex:0];
                NSString *  name = [nameElement stringValue];
                attachModel.attachmentsTitle = name;
                
                GDataXMLElement * contentElement = [[data elementsForName:@"内容"] objectAtIndex:0];
                NSString *  content = [contentElement stringValue];
                attachModel.attachmentsURL = content;
                
                [self.attachmentArray addObject:attachModel];
            }
        }
    }
    
    for (GDataXMLElement * subData in rootData) {
        NSArray * tempArray = [subData elementsForName:@"正文实体"];
        for (GDataXMLElement * element in tempArray) {
            NSArray *array = [element elementsForName:@"附件"];
            for (GDataXMLElement * data in array) {
                OAAttachmentsModel * attachModel = [[OAAttachmentsModel alloc]init];
                GDataXMLElement * nameElement = [[data elementsForName:@"名称"] objectAtIndex:0];
                NSString *  name = [nameElement stringValue];
                attachModel.attachmentsTitle = name;
                
                GDataXMLElement * contentElement = [[data elementsForName:@"内容"] objectAtIndex:0];
                NSString *  content = [contentElement stringValue];
                attachModel.attachmentsURL = content;
                
                [self.mainattachmentArray addObject:attachModel];
            }
        }
    }
    
    return detailModel;
    
}

-(OADetailDispatchModel *)getDetailModel2:(NSString*)dataString;
{
    NSData * data = [dataString dataUsingEncoding:NSUTF8StringEncoding];
    OADetailDispatchModel * detailModel = [[OADetailDispatchModel alloc]init];
    GDataXMLDocument *doc = [[GDataXMLDocument alloc] initWithData: data options:0 error:nil];
    //获取根节点（Users）
    GDataXMLElement *rootElement = [doc rootElement];
    //获取根节点下的节点（User）
    NSArray *rootData= [rootElement elementsForName:@"数据"];
    for (GDataXMLElement *data in rootData) {
        NSArray * tempArray = [data elementsForName:@"数据要素"];
        for (GDataXMLElement *data in tempArray) {
            GDataXMLElement *documentElement= [[data elementsForName:@"文档"] objectAtIndex:0];
            detailModel.document = [documentElement stringValue];
            
            
            
            GDataXMLElement *filestep= [[data elementsForName:@"填写意见环节"] objectAtIndex:0];
            detailModel.flow = [filestep stringValue];
            
            GDataXMLElement *fileId= [[data elementsForName:@"唯一标识"] objectAtIndex:0];
            detailModel.fileId = [fileId stringValue];
            
        }
    }
    //index。seston = 2
    for (GDataXMLElement * subData in rootData) {
        NSArray * tempArray = [subData elementsForName:@"数据实体"];
        for (GDataXMLElement * element in tempArray) {
            NSArray *array = [element elementsForName:@"附件"];
            for (GDataXMLElement * data in array) {
                OAAttachmentsModel * attachModel = [[OAAttachmentsModel alloc]init];
                GDataXMLElement * nameElement = [[data elementsForName:@"名称"] objectAtIndex:0];
                NSString *  name = [nameElement stringValue];
                attachModel.attachmentsTitle = name;
                
                GDataXMLElement * contentElement = [[data elementsForName:@"内容"] objectAtIndex:0];
                NSString *  content = [contentElement stringValue];
                attachModel.attachmentsURL = content;
                
                [self.attachmentArray addObject:attachModel];
            }
        }
    }
    
    for (GDataXMLElement * subData in rootData) {
        NSArray * tempArray = [subData elementsForName:@"正文实体"];
        for (GDataXMLElement * element in tempArray) {
            NSArray *array = [element elementsForName:@"附件"];
            for (GDataXMLElement * data in array) {
                OAAttachmentsModel * attachModel = [[OAAttachmentsModel alloc]init];
                GDataXMLElement * nameElement = [[data elementsForName:@"名称"] objectAtIndex:0];
                NSString *  name = [nameElement stringValue];
                attachModel.attachmentsTitle = name;
                
                GDataXMLElement * contentElement = [[data elementsForName:@"内容"] objectAtIndex:0];
                NSString *  content = [contentElement stringValue];
                attachModel.attachmentsURL = content;
                
                [self.mainattachmentArray addObject:attachModel];
            }
        }
    }
    
    return detailModel;
    
}


//获取解析得到的数据。
-(OADetailDispatchModel *)getDetailModel1:(NSString*)dataString;
{
    NSData * data = [dataString dataUsingEncoding:NSUTF8StringEncoding];
    OADetailDispatchModel * detailModel = [[OADetailDispatchModel alloc]init];
    GDataXMLDocument *doc = [[GDataXMLDocument alloc] initWithData: data options:0 error:nil];
    //获取根节点（Users）
    GDataXMLElement *rootElement = [doc rootElement];
    //获取根节点下的节点（User）
    NSArray *rootData= [rootElement elementsForName:@"数据"];
    for (GDataXMLElement *subData in rootData) {
        NSArray * tempArray = [subData elementsForName:@"数据要素"];
        for (GDataXMLElement *data in tempArray) {
            GDataXMLElement *documentElement= [[data elementsForName:@"文档"] objectAtIndex:0];
            detailModel.document = [documentElement stringValue];
            
            
            
           GDataXMLElement *filestep= [[data elementsForName:@"填写意见环节"] objectAtIndex:0];
            detailModel.flow = [filestep stringValue];
            
            GDataXMLElement *fileId= [[data elementsForName:@"唯一标识"] objectAtIndex:0];
            detailModel.fileId = [fileId stringValue];
            
        }
    }
    
    for (GDataXMLElement * subData in rootData) {
        NSArray * tempArray = [subData elementsForName:@"数据实体"];
        for (GDataXMLElement * element in tempArray) {
            NSArray *array = [element elementsForName:@"附件"];
            for (GDataXMLElement * data in array) {
                OAAttachmentsModel * attachModel = [[OAAttachmentsModel alloc]init];
                GDataXMLElement * nameElement = [[data elementsForName:@"名称"] objectAtIndex:0];
                NSString *  name = [nameElement stringValue];
                attachModel.attachmentsTitle = name;
                
                GDataXMLElement * contentElement = [[data elementsForName:@"内容"] objectAtIndex:0];
                NSString *  content = [contentElement stringValue];
                attachModel.attachmentsURL = content;
                
                [self.attachmentArray addObject:attachModel];
            }
        }
    }
    
    for (GDataXMLElement * subData in rootData) {
        NSArray * tempArray = [subData elementsForName:@"正文实体"];
        for (GDataXMLElement * element in tempArray) {
            NSArray *array = [element elementsForName:@"附件"];
            for (GDataXMLElement * data in array) {
                OAAttachmentsModel * attachModel = [[OAAttachmentsModel alloc]init];
                GDataXMLElement * nameElement = [[data elementsForName:@"名称"] objectAtIndex:0];
                NSString *  name = [nameElement stringValue];
                attachModel.attachmentsTitle = name;
                
                GDataXMLElement * contentElement = [[data elementsForName:@"内容"] objectAtIndex:0];
                NSString *  content = [contentElement stringValue];
                attachModel.attachmentsURL = content;
                
                [self.mainattachmentArray addObject:attachModel];
            }
        }
    }
    
    return detailModel;
    
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 3;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    switch (section) {
        case 0:
            return self.detailPatchModel.formArray.count;
            break;
        case 1:
            return self.mainattachmentArray.count;
        case 2:
            return self.attachmentArray.count;
        default:
            return 1;
            break;
    }
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.section == 0) {
        OADetailDisPatchCell * cell = [OADetailDisPatchCell cellWihtTableView:tableView];
   //     cell.textView.delegate = self;
        NSString * allString = self.detailPatchModel.formArray[indexPath.row];
        cell.detailModel = self.detailPatchModel;
        cell.allString = allString;
         [cell editStatus:self.isEditoring];
        return cell;
    }else{

        if (indexPath.section == 1) {
            static NSString * cellIdentifier = @"cellIdentifier";
            UITableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
            if (cell == nil) {
                cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier];
            }
            OAAttachmentsModel * model = self.mainattachmentArray[indexPath.row];
            cell.textLabel.text = model.attachmentsTitle;
            cell.textLabel.font = [UIFont systemFontOfSize:14];
            cell.textLabel.numberOfLines = 0;
            cell.textLabel.textColor = [UIColor colorWithRed:85/255.0 green:85/255.0  blue:85/255.0 alpha:1.0];
            return cell;
            
        }else{
            static NSString * cellIdentifier = @"cellId";
            UITableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
            if (cell == nil) {
                cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier];
            }
            OAAttachmentsModel * model = self.attachmentArray[indexPath.row];
            cell.textLabel.text = model.attachmentsTitle;
            cell.textLabel.font = [UIFont systemFontOfSize:14];
            cell.textLabel.numberOfLines = 0;
            cell.textLabel.textColor = [UIColor colorWithRed:85/255.0 green:85/255.0  blue:85/255.0 alpha:1.0];
            return cell;

        }

    }
    
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    if (indexPath.section == 0) {
        NSString * allString = self.detailPatchModel.formArray[indexPath.row];
        CGFloat height =  [allString boundingRectWithSize:CGSizeMake(KScreenWidth - 30, 0) options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName:[UIFont systemFontOfSize:16]} context:nil].size.height;
        if (height < 44) {
            height = 44;
        }
        return height + 10;
    }else{
        return 54;
    }
    
}
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    if (section==1) {
        UIView * bgView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, kScreenWidth, 30)];
        UILabel * label = [[UILabel alloc]initWithFrame:CGRectMake(10, 0, kScreenWidth, 21)];
        label.text = @"正文";
       // label.backgroundColor = [UIColor grayColor];
//        label.font = [UIFont systemFontOfSize:14];
//        label.textColor = [UIColor colorWithRed:85/255.0 green:85/255.0  blue:85/255.0 alpha:1.0];
 label.font = [UIFont systemFontOfSize:16];
        label.textColor = [UIColor blackColor];
        [bgView addSubview:label];
//OAAttachmentsModel * model = self.mainattachmentArray[0];
//   if (_mainattachmentArray.count>0) {
//            OAAttachmentsModel * model = self.mainattachmentArray[0];
//            if ([model.attachmentsTitle length]>0) {
//        return bgView;
//
//}
//else{
//        return nil;
//
//}
//}else{
//        if (!(self.mainattachmentArray.count>0)) {
//            label.hidden = YES;
//        }else{
//            label.hidden = NO;
//        }
//         if (!(self.mainattachmentArray.count>0)) {
//        return nil;
//        }else{
//        return bgView;
//        }
//        }
        return bgView;
    }
     if (section==2) {
        UIView * bgView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, KScreenWidth, 30)];
        UILabel * label = [[UILabel alloc]initWithFrame:CGRectMake(10,5, KScreenWidth, 21)];
        label.text = @"附件";
         UIView *lineview = [[UIView alloc]initWithFrame:CGRectMake(0, 0, KScreenWidth, .5)];
        lineview.backgroundColor = [UIColor colorWithHexString:@"C8C7CC"];
if (_mainattachmentArray.count>0) {

}else{
            [bgView addSubview:lineview];

}
//        label.backgroundColor = [UIColor grayColor];
//        label.font = [UIFont systemFontOfSize:14];
//        label.textColor = [UIColor colorWithRed:85/255.0 green:85/255.0  blue:85/255.0 alpha:1.0];
 label.font = [UIFont systemFontOfSize:16];
        label.textColor = [UIColor blackColor];
        [bgView addSubview:label];
//         if (_attachmentArray.count>0) {
//            OAAttachmentsModel * model = self.attachmentArray[0];
//            if ([model.attachmentsTitle length]>0) {
//        return bgView;
//
//}
//else{
//        return nil;
//
//}
//}else{
//     if (!(self.attachmentArray.count>0)) {
//            label.hidden = YES;
//        }else{
//            label.hidden = NO;
//        }
//         if (!(self.attachmentArray.count>0)) {
//        return nil;
//        }else{
//        return bgView;
//        }
//        }
        return bgView;

}
    return nil;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    if (section==1) {
//    if (_mainattachmentArray.count>0) {
//            OAAttachmentsModel * model = self.mainattachmentArray[0];
//            if ([model.attachmentsTitle length]>0) {
//         return 21;
//
//}
//else{
// return 0.001;
//[_mainattachmentArray removeAllObjects];
//
//}
//}else{
//    if (_mainattachmentArray.count !=0) {
//     return 21;
//
//}else{
//
// return 0.001;
//
//
//}
//    }
    return 30;
           }
    if (section==2) {
//        if (_attachmentArray.count>0) {
//            OAAttachmentsModel * model = self.attachmentArray[0];
//            if ([model.attachmentsTitle length]>0) {
//         return 21;
//
//}
//else{
//[_attachmentArray removeAllObjects];
// return 0.001;
//
//}
//}else{
// if (_attachmentArray.count!=0) {
//     return 21;
//
//}else{
//
// return 0.001;
//
//
//}}
return 30;
    }
    return 0.001;
}


-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    if (indexPath.section == 1) { //下载附件 查看附件信息
        OAAttachmentsModel * model = self.mainattachmentArray[indexPath.row];
//        [self openFileURL:model.attachmentsURL];
 fujianwebViewController *vc = [[fujianwebViewController alloc]init];
        vc.url = model.attachmentsURL;
        [self.navigationController pushViewController:vc animated:YES];
    }else if (indexPath.section == 2){
        OAAttachmentsModel * model = self.attachmentArray[indexPath.row];
//        [self openFileURL:model.attachmentsURL];
 fujianwebViewController *vc = [[fujianwebViewController alloc]init];
        vc.url = model.attachmentsURL;
        [self.navigationController pushViewController:vc animated:YES];
    }
    
}
-(void)openFileURL:(NSString*)url{
    NSString * stringurl = [url stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    self.attacmentURL =  [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject] stringByAppendingPathComponent:[url lastPathComponent]]; //附件路径
 
    if ([self isExtistFilePathWithFileName:[[NSURL URLWithString:stringurl] lastPathComponent]]) { //已经存在附件
        QLPreviewController *previewoCntroller = [[QLPreviewController alloc] init] ;
        previewoCntroller.delegate=self;
        previewoCntroller.dataSource=self;
        previewoCntroller.navigationItem.rightBarButtonItem=nil;
                                    previewoCntroller.hidesBottomBarWhenPushed = YES;

        [self.navigationController pushViewController: previewoCntroller animated:YES];
        
    }else{
        MBProgressHUD * hud  =  [MBProgressHUD showHUDAddedTo:self.view animated:YES];
        hud.labelText = @"下载中...";
        NSURLRequest * request = [NSURLRequest requestWithURL:[NSURL URLWithString:stringurl]];
        [self.webView loadRequest:request];
    }
    
}

#pragma mark PreviewDataSource
//第一个方法是设定一组文档浏览的个数，会影响到在文档预览中的上/下一页。
-(NSInteger)numberOfPreviewItemsInPreviewController:(QLPreviewController *)controller {
    return 1;
}
//第二个方法是指定文档预览的文件路径
-(id<QLPreviewItem>)previewController:(QLPreviewController *)controller previewItemAtIndex:(NSInteger)index {
    
    return [NSURL fileURLWithPath:self.attacmentURL];
}

-(BOOL)isExtistFilePathWithFileName:(NSString*)fileName{
    NSString * file = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
    NSString * filePath = [file stringByAppendingPathComponent:fileName];
    NSFileManager * fileManager = [NSFileManager defaultManager];
    if ([fileManager fileExistsAtPath:filePath] && fileName.length != 0) {
        return YES;
    }else{
        return NO;
    }
    
}

- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType{
    NSURL * requestedURL = [request URL];
    NSData * fileData = [[NSData alloc] initWithContentsOfURL:requestedURL];
    NSString * filePath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
     [fileData writeToFile:[filePath stringByAppendingPathComponent:[requestedURL lastPathComponent]] atomically:YES];
      return YES;
}
- (void)webViewDidStartLoad:(UIWebView *)webView{
    
    
}
- (void)webViewDidFinishLoad:(UIWebView *)webView{
    [MBProgressHUD hideAllHUDsForView:self.view animated:YES];
    QLPreviewController *previewoCntroller = [[QLPreviewController alloc] init] ;
    previewoCntroller.delegate=self;
    previewoCntroller.dataSource=self;
    [self.navigationController pushViewController: previewoCntroller animated:YES];
}
- (void)webView:(UIWebView *)webView didFailLoadWithError:(NSError *)error{
    
    [MBProgressHUD hideAllHUDsForView:self.view animated:YES];
}

- (void)dealloc{

            [[NSNotificationCenter defaultCenter] postNotificationName:@"refreshData" object:nil]; //刷新发件箱，收件箱 数据

}


@end
